/*
 * Copyright 2011 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.gtugs.web;

import org.gtugs.domain.Chapter;
import org.gtugs.service.ChapterManager;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author van@gtugs.org (Van Riper)
 */
public class KmlMapController implements Controller, MessageSourceAware {

  private ChapterManager chapterManager;

  private MessageSource messageSource;

  @Override
  public void setMessageSource(MessageSource messageSource) {
    this.messageSource = messageSource;
  }

  @SuppressWarnings("unchecked")
  public ModelAndView handleRequest(HttpServletRequest request,
      HttpServletResponse response) throws ServletException {

    List<List<Chapter>> modelData = null;
    List<List<Chapter>> chaptersGroupedByCountry = chapterManager.getChaptersGroupedByCountry();
    String countryStr = request.getParameter("country");

    if (countryStr == null) {
      modelData = chaptersGroupedByCountry;
    } else {
      for (List<Chapter> chaptersForOneCountry: chaptersGroupedByCountry) {
        Chapter chapter = chaptersForOneCountry.get(0);
        if (chapter.getCountry().contentEquals(countryStr)) {
          List<List<Chapter>> singleCountryData = new ArrayList<List<Chapter>>();
          singleCountryData.add(chaptersForOneCountry);
          modelData = singleCountryData;
          break;
        }
      }
    }

    // Hack after valiant effort to make the View class MessageSourceAware unsuccessfully.
    KmlMapView view = new KmlMapView();
    view.setMessageSource(messageSource);

    return new ModelAndView(view, KmlMapView.MODEL_DATA_KEY, modelData);
  }

  public void setChapterManager(ChapterManager chapterManager) {
    this.chapterManager = chapterManager;
  }
}
